using System.IdentityModel.Tokens.Jwt;
using IdentityModel;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace WebAClient
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            //http 下 登录成功后跳转 http://localhost:port/signin-oidc 时 服务器500错误, 同时 app.UseCookiePolicy(); 不要忘记写
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
            //});
            services.ConfigureNonBreakingSameSiteCookies();

            services.AddControllers();


            //下面2行不知道干什么的
            //JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
            //https://blog.lcrun.com/wei-shi-yao-yao-shi-yong-jwtsecuritytokenhandler-defaultinboundclaimtypemap-clear/
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            #region IdentityServer4--Implicit (教程里的)
            //要添加IdentityServer4.AccessTokenValidation.dll
            //services.AddAuthentication("Bearer")
            //    .AddIdentityServerAuthentication(options =>
            //    {
            //        options.Authority = "http://localhost:5000";
            //        options.ApiName = "api1";
            //        options.RequireHttpsMetadata = false;
            //    });
           
            #endregion

            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;//Cookies
                    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                    //options.DefaultChallengeScheme = "oidc";
                })
                 .AddIdentityServerAuthentication(options =>
                 {
                     options.Authority = "http://localhost:5000";
                     options.ApiName = "api1";
                     options.RequireHttpsMetadata = false;
                 })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)//Cookies
                .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
                //.AddOpenIdConnect("oidc", options =>
                {
                    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;//Cookies
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    options.ClientId = "mvc_code_client";
                    options.ClientSecret = "secret";
                    options.SaveTokens = true;
                    //options.ResponseType = "code"; //这行注释 就 不能跳转到登录页
                    options.ResponseType = OpenIdConnectResponseType.Code;

                    options.Scope.Clear();
                    options.Scope.Add("api1");
                    options.Scope.Add(OidcConstants.StandardScopes.OpenId);
                    options.Scope.Add(OidcConstants.StandardScopes.Profile);
                    options.Scope.Add(OidcConstants.StandardScopes.Email);
                    options.Scope.Add(OidcConstants.StandardScopes.Phone);
                    options.Scope.Add(OidcConstants.StandardScopes.Address);
                    options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);


                    // Boolean用于设置处理程序在从令牌终结点接收的id令牌创建标识后是否应转到user info endpoint以检索其他声明。默认值为“false”。
                    //options.GetClaimsFromUserInfoEndpoint = true;

                });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 在任何其他可能编写cookie的中间件之前添加此项
            app.UseCookiePolicy();//使上面的services.Configure<CookiePolicyOptions>生效

            //顺序不能搞错 ，UseAuthentication(前) UseAuthorization(后)  否则 死循环 
            app.UseAuthentication();  // 解决 identity server4 登录成功跳回到signin-oidc得到404 的问题


            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
